import { PlusCircleOutlined } from "@ant-design/icons";
import { Rate, message, Spin, Tooltip, Tag } from "antd";
import dayjs from "dayjs";
import { FC, useEffect, useState } from "react";
import styles from "../../styles.less";
import Https from "@/utils/Https";
import {
  weekNameList,
  getStyle,
  secondsList,
  mergeArrays,
  courseTypeList,
} from "../../interface";
const SortCourse: FC<any> = (props) => {
  const {
    addWork,
    venueObj,
    roomInfo,
    defaultWeekValue,
    defaultTime,
    sortReload,
    isScroll = true,
    isFull,
  } = props;
  const [weekTimeList, setWeekTimeList] = useState([]);
  const [loading, setLoading] = useState(false);
  const [week, setWeek] = useState([]);
  const [scrollTop, setScrollTop] = useState(0);
  const [windowHeigth, setWindowHeight] = useState(window.innerHeight);
  //获取X轴数据
  const getXaxle = async (id, defaultWeekValue) => {
    let params = {
      weekType: "2",
      pramDate: dayjs(defaultWeekValue).format("YYYY-MM-DD"),
      venueId: id,
    };
    setLoading(true);
    let res = await Https.post("/course/sched/timeWeek", params, true);
    if (res.code == 200) {
      let objList = [{ date: "" }];
      if (res.data.length > 0) {
        res.data.map((item) => {
          objList.push({ ...item });
        });
        setWeekTimeList(objList);
      }
    } else {
      setWeekTimeList([]);
      message.error(res.msg);
    }
    setLoading(false);
  };
  //获取排课表数据
  const getData = async (venueId, defaultTime, classRoom) => {
    let params = {
      venueId,
      courseType: "2",
      classRoom,
      startTimeSlot: defaultTime.startTime,
      endTimeSlot: defaultTime.endTime,
    };
    setLoading(true);
    let res: any = await Https.post("/course/sched/scheduleList", params, true);
    setLoading(false);
    if (res.code == 200 && res.data) {
      let objList: any = [];
      let objList2: any = [];
      if (res.data.length > 0) {
        res.data.map((item) =>
          objList.push({
            week: dayjs(item.date).day() == 0 ? 7 : dayjs(item.date).day(),
            ...item,
          })
        );
        objList.sort(function (a, b) {
          return dayjs(a.date) - dayjs(b.date);
        });
        setWeek(objList);
      } else {
        setWeek([]);
      }
      if (isScroll) {
        let result: any = await Https.post(
          "/classRoomOccupancy/scheduleClassRoomOccupancyList",
          params,
          true
        );
        if (result.code == 200 && result.data) {
          if (result.data.length > 0) {
            result.data.map((item) =>
              objList2.push({
                week: dayjs(item.date).day() == 0 ? 7 : dayjs(item.date).day(),
                ...item,
              })
            );
            objList2.sort(function (a, b) {
              return dayjs(a.date) - dayjs(b.date);
            });
            let arr3 = mergeArrays(objList, objList2, "date");
            setWeek(arr3);
          }
        }
      }
    } else {
      setWeek([]);
      message.error(res.msg);
    }
  };
  useEffect(() => {
    if (venueObj.id && defaultWeekValue) {
      getXaxle(venueObj.id, defaultWeekValue);
    }
  }, [venueObj, defaultWeekValue]);
  useEffect(() => {
    if (venueObj.id && defaultTime && roomInfo.id) {
      getData(venueObj.id, defaultTime, roomInfo.id);
    }
  }, [venueObj, defaultTime, roomInfo, sortReload]);
  const handleResize = () => {
    setWindowHeight(window.innerHeight);
  };
  useEffect(() => {
    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, []);
  return (
    <Spin spinning={loading}>
      <div
        className={styles.timaMain}
        style={{
          height: isFull
            ? windowHeigth - 90 + "px"
            : isScroll
            ? "500px"
            : "auto",
        }}
        onScroll={(e) => {
          let { scrollTop } = e.target;
          setScrollTop(scrollTop);
        }}
      >
        <div
          className={`${styles.timeBox} ${
            scrollTop > 60 ? styles.strikShadow : ""
          }`}
        >
          {weekTimeList &&
            weekTimeList.length > 0 &&
            weekTimeList.map((item, index) => (
              <div className={styles.time_header} key={index}>
                {index == 0 ? (
                  "时间段"
                ) : (
                  <span>
                    {dayjs(item.date).format("MM-DD")} 周{weekNameList[index]}
                    {isScroll && (
                      <>
                        {item.isRest == 0 && roomInfo.roomStatus == "0" ? (
                          <PlusCircleOutlined
                            onClick={() => {
                              addWork("add", index, item.date);
                            }}
                            style={{ marginLeft: "5px", color: "#1677ff" }}
                          />
                        ) : (
                          <Tooltip title="时间过期或场馆当天放假">
                            <PlusCircleOutlined
                              style={{ marginLeft: "5px", color: "#999999" }}
                            />
                          </Tooltip>
                        )}
                      </>
                    )}
                  </span>
                )}
              </div>
            ))}
        </div>
        <div className={styles.boxHidden}>
          <div className={styles.timeContent}>
            {secondsList.map((e, index) => (
              <div key={index} className={styles.timeHr}>
                <div className={styles.timeSecond}>{e}</div>
                {weekNameList.map(
                  (i, cindex) =>
                    cindex > 0 && (
                      <div key={cindex} className={styles.timeWeek}></div>
                    )
                )}
              </div>
            ))}
            {week &&
              week.length > 0 &&
              week.map(
                (e, eindex) =>
                  e.list &&
                  e.list.length > 0 &&
                  e.list.map((c, cindex) => (
                    <div
                      className={`${styles.card_resize} ${
                        c.isExpired == 1 ? styles.hasExpired : ""
                      }  ${!isScroll && c.occupiedType ? styles.noneBox : ""}`}
                      style={
                        getStyle(e, {
                          ...c,
                          colour: c.colour ? c.colour : "#b5b6b8",
                        }).objStyle
                      }
                      onClick={() => {
                        if (c.occupiedType) {
                          return;
                        }
                        addWork("edit", e.week, e.date, c);
                      }}
                    >
                      {c.occupiedType && (
                        <div
                          className={styles.card_item}
                          style={{ marginTop: "4px" }}
                        >
                          {dayjs(c.startTimeSlot).format("HH:mm")}~
                          {dayjs(c.endTimeSlot).format("HH:mm")}(
                          {c.status == 1 ? "已占用" : "已完成"})
                          <Tag>{courseTypeList[c.occupiedType]}</Tag>
                        </div>
                      )}
                      {!c.occupiedType && (
                        <>
                          <div className={styles.card_item}>
                            {dayjs(c.startTimeSlot).format("HH:mm")}~
                            {dayjs(c.endTimeSlot).format("HH:mm")}
                          </div>
                          <div className={styles.card_name}>{c.courseName}</div>
                          <div className={styles.card_teach}>
                            {c.courseCoachName}
                          </div>
                          <div className={styles.card_rate}>
                            <Rate disabled value={c.courseDifficulty} />
                          </div>
                        </>
                      )}
                    </div>
                  ))
              )}
          </div>
        </div>
      </div>
    </Spin>
  );
};
export default SortCourse;
